"""GSP管理的公共类"""

from datetime import datetime

from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError
from odoo.addons import decimal_precision as dp


class NDBase(models.AbstractModel):
    """通用字段"""
    _name = 'nd.base'
    _description = 'ND基类'

    state = fields.Selection([('draft', '草稿'), ('confirm', '审核')], string="状态", default="draft", track_visibility='onchange')
    confirm_user = fields.Many2one('res.users', string="审核人", readonly=True, track_visibility='onchange')
    confirm_time = fields.Datetime('审核时间', readonly=True, track_visibility='onchange')

    @api.multi
    def confirm(self):
        """审核单据，记录审核人和审核时间"""
        draft_orders = self.filtered(lambda x: x.state in ['draft'])
        draft_orders.write({'state': 'confirm',
                            'confirm_user': self.env.user.id,
                            'confirm_time': datetime.now()})

    @api.multi
    def unconfirm(self):
        """取消审核，状态回归草稿"""
        confirmed_orders = self.filtered(lambda x: x.state in ['confirm'])
        confirmed_orders.write({'state': 'draft',
                                'confirm_user': False,
                                'confirm_time': False})


class GspBase(models.AbstractModel):
    """设置此类的原因是部分字段，例如name、type等是某些系统model的字段，将这部分统一集中
    在这里。因此这个类只给新建model用，系统原有model一般不用此类"""
    _name = 'gsp.base'
    # _inherit = ['nd.base']
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _description = 'GSP基类'

    type = fields.Selection([('medicine', '药品'), ('instrument', '医疗器械')],
                            string="用于", required=True, readonly=True,
                            states={'draft': [('readonly', False)]}, track_visibility='onchange')
    name = fields.Char('名称', readonly=True, states={'draft': [('readonly', False)]}, track_visibility='onchange')
    code = fields.Char('编号', readonly=True, states={'draft': [('readonly', False)]}, track_visibility='onchange')


class GspManageBase(models.AbstractModel):
    """GSP管理相关通用字段"""
    _name = 'gsp.manage.base'
    _inherit = ['nd.base']
    _description = 'GSP管理基类'

    gsp_management = fields.Boolean('是否需要GSP管理', readonly=True,
                                    states={'draft': [('readonly', False)]}, track_visibility='onchange')
    can_use = fields.Boolean('是否可用', help="用于GSP控制流程", compute="_compute_can_use", store=True)

    @api.depends('state', 'gsp_management')
    def _compute_can_use(self):
        """根据传入的对象，计算此对象是否可用于业务。如果是需要GSP管理，则需要检查审核是否通过。否则不检查"""
        for order in self:
            order.can_use = (not order.gsp_management) or (order.state in ['confirm'])









